package rmsstream;

import java.util.Vector;

public class RMSBuffer implements Runnable {

	public final int STATUS_PRELOADING = 0;
	public final int STATUS_PLAYING = 1;
	private int STATUS = STATUS_PRELOADING;

	private Vector playerqueue;
	private Vector videoqueue;

	int currPosition = 0;
	RMSVideoPlayer currPlayer = null;

	public RMSBuffer() {

		playerqueue = new Vector();
		videoqueue = new Vector();

		registerPlayer(new RMSVideoPlayer(this, 1));
		registerPlayer(new RMSVideoPlayer(this, 2));
		// registerPlayer(new RMSVideoPlayer(this, 3));

	}

	public void run() {

		System.out.println("------------RUN RMSBUFFER-------------");

		while (true) {

			for (int i = 0; i < playerqueue.size(); i++) {

				if (((RMSVideoPlayer) playerqueue.elementAt(i)).getSTATUS() == RMSVideoPlayer.STATUS_EMPTY) {
					System.out.println("------------RUN RMSBUFFER-------------"
							+ i);

					Thread newThread = new Thread((RMSVideoPlayer) playerqueue
							.elementAt(i));
					newThread.start();
					// ((RMSVideoPlayer) playerqueue.elementAt(i)).start();
				}
				if (currPlayer == null) {

					if (((RMSVideoPlayer) playerqueue.elementAt(i)).getSTATUS() == RMSVideoPlayer.STATUS_WAITING) {
						currPlayer = ((RMSVideoPlayer) playerqueue.elementAt(i));
						if (currPlayer.isFinished_() == false) {
							currPlayer.play();
						}
					}

				} else if (currPlayer.getSTATUS() == RMSVideoPlayer.STATUS_USED) {
					currPlayer = ((RMSVideoPlayer) playerqueue.elementAt(i));
					if (currPlayer.isFinished_() == false) {
						currPlayer.play();
					}
				}
			}

			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	public void registerPlayer(RMSVideoPlayer player) {
		playerqueue.addElement(player);
	}

	public void unregisterPlayer(RMSVideoPlayer player) {
		playerqueue.removeElement(player);

	}

	public void addVideo(String url, String mime) {
		System.out.println("ADDING VIDEO to queue: " + url);
		videoqueue.addElement(new VideoContentDescriptor(url, mime));
	}

	public synchronized VideoContentDescriptor getNextPlayable() {
		System.out.println(currPosition + " " + videoqueue.size());
		if (currPosition < videoqueue.size()) {
			VideoContentDescriptor vcd = (VideoContentDescriptor) videoqueue
					.elementAt(currPosition);
			currPosition++;
			return vcd;
		} else {
			return null;
		}

	}

	public int getSTATUS() {
		return STATUS;
	}
}
